<?php

class PagesLib extends ALib
{
	// ------------------------------------------------------------------------------------
	/**
	 * @static
	 * @return PlacesLib
	 */
	protected static $_instance = NULL;
	public static function i()
	{
		return NULL === self::$_instance ? self::$_instance = new self() : self::$_instance;
	}

	// ------------------------------------------------------------------------------------
	/**
	 * @param  $page_name
	 * @return
	 */
	public function getPage($page_name)
	{
		if(empty($page_name))
		{
			$page_name = 'index';
		}
		$Criteria = new CDbCriteria;
		$Criteria->addColumnCondition(array('`page_name`' => $page_name));
		$Criteria->addCondition('`page_hidden` = 0');
		return $this->find($Criteria);
	}

	// ------------------------------------------------------------------------------------
	/**
	 * @param CDbCriteria $Criteria
	 * @param  $totalRows
	 * @return array
	 */
	protected function _doFindAll(CDbCriteria $Criteria, &$totalRows = NULL)
	{
		if(NULL !== $totalRows)
		{
			$Criteria->select = 'SQL_CALC_FOUND_ROWS ' . $Criteria->select;
		}

		$Criteria->alias = 'p';
		$queryRows = $this->_prepareSelect(Yii::app()->params['TABLES']['pages'], $Criteria);

		if(NULL !== $totalRows)
		{
			$totalRows = self::db()->createCommand('SELECT FOUND_ROWS()')->queryScalar();
		}

		// Готовим парсер групп
		$groups = array();
		$groupsFile = Yii::app()->params['PATH_TO_GROUPS_FILE'];
		if(file_exists($groupsFile) && is_readable($groupsFile))
		{
			$groups = json_decode(file_get_contents($groupsFile));
		}
		foreach($groups as $groupName => $images)
		{
			if(!empty($images))
			{
				$str = '<ul class="ul-images">';
				foreach($images as $imageName => $imageData)
				{
					$str .= '<li><a class="x-hash" xhash="p:' . $groupName . '-' . $imageName . '.jpg" href="/photos/' . $groupName . '/' . $imageName . '.jpg"><img class="i-photo" src="/photos/' . $groupName . '/' . $imageName . '-icon.jpg" width="150" height="113" alt="" /></a></li>';
				}
				$str .= '</ul>';
			}

			$substitutions['[group]' . $groupName . '[/group]'] = $str;
		}

		if($_SERVER['REMOTE_ADDR'] == '79.135.201.127')
		{
			//var_dump($substitutions);
		}

		$result = array();
		foreach($queryRows as $row)
		{
			if(!empty($substitutions))
			{
				$row['page_content_parsed'] = str_replace(array_keys($substitutions), $substitutions, $row['page_content']);
				$row['page_content_parsed'] = preg_replace('#\[group\][a-z0-9\-_]+\[\/group\]#', '', $row['page_content_parsed']);
			}
			$result[] = new Page($row);
		}
		
		return $result;
	}

	// ------------------------------------------------------------------------------------
}